package com.cnooc.aicv.lmapp.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ContentDeserializer extends JsonDeserializer<Content> {

    @Override
    public Content deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        JsonNode node = mapper.readTree(p);

        if (node.isArray()) {
            // 处理数组类型
            List<ComplexContent.ComplexContentItem> complexContentItems = new ArrayList<>();
            for (JsonNode element : node) {
                ComplexContent.ComplexContentItem item = mapper.treeToValue(element, ComplexContent.ComplexContentItem.class);
                complexContentItems.add(item);
            }

            ComplexContent complexContent = new ComplexContent();
            complexContent.setContent(complexContentItems);
            return complexContent;
        } else if (node.isTextual()) {
            // 处理字符串类型
            SimpleContent simpleContent = new SimpleContent();
            simpleContent.setContent(node.asText());
//            return simpleContent;
            return new SimpleContent(node.asText());
        } else {
            throw new IllegalArgumentException("Unsupported content type: " + node.getNodeType());
        }
    }
}